package me.pplay.playtalk.util.fileUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.pplay.playtalk.bean.Face;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;

/*
 * sunny
 * 文件辅助类
 */
public class FileUtil {

	@SuppressWarnings("unused")
	private static final String NO_CACHE_PATH = "/.nomedia";
	private static FileUtil fileUtils = new FileUtil();

	public static FileUtil getInstance() {
		return fileUtils;
	}

	public FileUtil() {
	}

	/*
	 * 检查给定的路径文件是否存在
	 */
	public static boolean isExistFile(String strFile) {
		File f = new File(strFile);
		return f.exists();
	}

	public static void mkdir(String path) {
		File dir = new File(path);
		if (!dir.exists() || !dir.isDirectory()) {
			dir.mkdir();
		}
	}
	
	public static boolean createFile(String path){
		File f = new File(path);
		try {
			return f.createNewFile();
		} catch (IOException e) {
		}
		return false;
	}
	
	
	public static void rename(String oldFilePath, String newFilePath) {
		File file = new File(oldFilePath);
		File newFile = new File(newFilePath);

		file.renameTo(newFile);
		file.delete();
	}

	public static boolean delete(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			// Log.i("TEST", "delete()"+filePath);
			return file.delete();
		}
		return false;
	}

	/**
	 * 删除文件夹里面的所有文件
	 * 
	 * @param path
	 *            String 文件夹路径 如 c:/fqf
	 */
	public static void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
//			if(Globals.isCancelDeleteFile)
//				break;
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
			}
		}
	}

	/**
	 * 删除文件夹
	 * 
	 * @param filePathAndName
	 *            String 文件夹路径及名称 如c:/fqf
	 * @param fileContent
	 *            String
	 * @return boolean
	 */
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹

		} catch (Exception e) {
			System.out.println("删除文件夹操作出错");
			e.printStackTrace();

		}
	}

	public static void writeToFile(String filePath, byte[] bytes) {
		try {
			File file = new File(filePath);
			if (!file.isFile()) {
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(file);// openFileOutput(filePath,MODE_PRIVATE);
			fos.write(bytes);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//获取文件夹的大小
	 public static long getFileSize(File f)throws Exception//取得文件夹大小
	    {
	        long size = 0;
	        File flist[] = f.listFiles();
	        for (int i = 0; i < flist.length; i++)
	        {
	            if (flist[i].isDirectory())
	            {
	                size = size + getFileSize(flist[i]);
	            } else
	            {
	                size = size + flist[i].length();
	            }
	        }
	        return size;
	 }
	 
	 public static String FormetFileSize(String filePath) {//转换文件大小
		 System.out.println("yuanfile::"+filePath);
		 String fileSizeString = "";
		 try{
		 	File file = new File(filePath);
			if(!file.isFile())
				file.createNewFile();
		    long fileS 		 = getFileSize(file);
	        DecimalFormat df = new DecimalFormat("#.00");
	        if(fileS == 0){
	        	fileSizeString ="0M";
	        }else if (fileS < 1024) {
	            fileSizeString = df.format((double) fileS) + "B";
	        } else if (fileS < 1048576) {
	            fileSizeString = df.format((double) fileS / 1024) + "K";
	        } else if (fileS < 1073741824) {
	            fileSizeString = df.format((double) fileS / 1048576) + "M";
	        } else {
	            fileSizeString = df.format((double) fileS / 1073741824) + "G";
	        }
	        System.out.println("yuanfile:"+fileS +"  "+fileSizeString);
		 }catch (Exception e) {
		 }
	      return fileSizeString;
	    }
	 
	 
	 /** 
	     * 文字转图片 
	     * @param (String) content传入文字 
	     * @param (Context) c 
	     * @return 
	     */  
	 public static SpannableString strToImage(String content,Context c){  
	        SpannableString ss  = new SpannableString(content);  
	        System.out.println(content.length());  
	        int start=0;  
	        int end=0;  
	        Pattern pattern=Pattern.compile("\\([^\\)]+\\)");  
	        String str="";  
	        Matcher m=pattern.matcher(content);  
	        while(m.find()){  
	            start=start+str.length()+content.indexOf("(");  
	            end= start+m.group().length()-1;  
	            str=m.group();  
	            replaceImage(c, str, ss,start,end);  
	            content=content.substring(content.indexOf(m.group())+m.group().length());  
	            m=pattern.matcher(content);  
	        }  
	        return ss;  
	    }  

		public static void replaceImage(Context c,String content,SpannableString ss,int starts,int end){  
	           try {  
//	        	   String key 			= content.replace("[", "").replace("]", "");
	        	   String key 			= content;
	        	   if(Face.getInstance(c).faceMap.containsKey(key)){
		               Drawable drawable 	= c.getResources().getDrawable(Face.getInstance(c).faceMap.get(key));    
		               if (drawable != null) {  
		                   drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());   
		                   ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);    
		                   ss.setSpan(span, starts,end + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
		               }  
	        	   }
	           } catch (Exception ex){  
	                 
	           }  
	   }
}